# MySQL Password Reset Script
Write-Host "Resetting MySQL root password..." -ForegroundColor Green

# Stop MySQL service
Write-Host "Stopping MySQL service..." -ForegroundColor Yellow
Stop-Service mysql -Force

# Wait a moment
Start-Sleep -Seconds 3

# Start MySQL in safe mode (skip grant tables)
Write-Host "Starting MySQL in safe mode..." -ForegroundColor Yellow

# Find MySQL installation
$mysqlPath = Get-ChildItem "C:\Program Files\MySQL" -Recurse -Name "mysqld.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
if ($mysqlPath) {
    $mysqlPath = "C:\Program Files\MySQL\$mysqlPath"
} else {
    Write-Host "MySQL not found in Program Files, trying Chocolatey installation..." -ForegroundColor Yellow
    $mysqlPath = Get-ChildItem "C:\ProgramData\chocolatey\lib\mysql\tools" -Recurse -Name "mysqld.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($mysqlPath) {
        $mysqlPath = "C:\ProgramData\chocolatey\lib\mysql\tools\$mysqlPath"
    }
}

if ($mysqlPath) {
    Write-Host "Found MySQL at: $mysqlPath" -ForegroundColor Green
    
    # Start MySQL in safe mode
    Start-Process -FilePath $mysqlPath -ArgumentList "--skip-grant-tables" -WindowStyle Hidden
    
    # Wait for MySQL to start
    Start-Sleep -Seconds 10
    
    # Reset password
    Write-Host "Resetting root password..." -ForegroundColor Yellow
    
    # Find mysql client
    $mysqlClientPath = Get-ChildItem "C:\Program Files\MySQL" -Recurse -Name "mysql.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($mysqlClientPath) {
        $mysqlClientPath = "C:\Program Files\MySQL\$mysqlClientPath"
    } else {
        $mysqlClientPath = Get-ChildItem "C:\ProgramData\chocolatey\lib\mysql\tools" -Recurse -Name "mysql.exe" -ErrorAction SilentlyContinue | Select-Object -First 1
        if ($mysqlClientPath) {
            $mysqlClientPath = "C:\ProgramData\chocolatey\lib\mysql\tools\$mysqlClientPath"
        }
    }
    
    if ($mysqlClientPath) {
        # Reset password
        & $mysqlClientPath -u root -e "FLUSH PRIVILEGES;"
        & $mysqlClientPath -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED BY 'root123';"
        & $mysqlClientPath -u root -e "FLUSH PRIVILEGES;"
        
        Write-Host "Password reset completed!" -ForegroundColor Green
    } else {
        Write-Host "MySQL client not found!" -ForegroundColor Red
    }
    
    # Stop safe mode MySQL
    Get-Process mysqld -ErrorAction SilentlyContinue | Stop-Process -Force
    
    # Wait a moment
    Start-Sleep -Seconds 3
    
    # Start MySQL service normally
    Write-Host "Starting MySQL service normally..." -ForegroundColor Yellow
    Start-Service mysql
    
} else {
    Write-Host "MySQL installation not found!" -ForegroundColor Red
}

Write-Host "MySQL password reset process completed!" -ForegroundColor Green
Write-Host "Try connecting with:" -ForegroundColor Cyan
Write-Host "Username: root" -ForegroundColor White
Write-Host "Password: root123" -ForegroundColor White
